package com.hdu.clj.dncard

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.text.isDigitsOnly
import com.hdu.clj.dncard.R
import com.hdu.clj.dncard.database.HeroDatabase
import com.hdu.clj.dncard.database.UserDatabase
import com.hdu.clj.dncard.databaseUtil.UserDatabaseUtil
import com.hdu.clj.dncard.util.ActivityCollector
import com.hdu.clj.dncard.util.User
import kotlinx.android.synthetic.main.activity_reg.*
import java.io.*

class RegActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reg)
        ActivityCollector.addActivity(this)

        if (agreeReg.isChecked){
            reg.isEnabled = true
            reg.isClickable = true
            reg.setBackgroundColor(Color.parseColor("#3BFFC022"))
        }
        else{
            reg.isEnabled = false
            reg.isClickable = false
            reg.setBackgroundColor(Color.parseColor("#CECFD8"))
        }
        agreeReg.setOnClickListener {
            if (agreeReg.isChecked){
                reg.isEnabled = true
                reg.isClickable = true
                reg.setBackgroundColor(Color.parseColor("#3BFFC022"))
            }
            else{
                reg.isEnabled = false
                reg.isClickable = false
                reg.setBackgroundColor(Color.parseColor("#CECFD8"))
            }
        }


        val userPass = passMakeLog.text
        val userRePass = rePassLog.text
        val userAcc = accMakeLog.text
        var ver = 1
        reg.setOnClickListener {
            val dbHelper = UserDatabase(this,"Users.db",1)
            val db = dbHelper.writableDatabase
            if (userPass.isNotEmpty()&&userRePass.isNotEmpty()&&userAcc.isNotEmpty()){
                if (!withSimbol(userAcc.toString())){
                    if (userPass.toString().equals(userRePass.toString())) {
                        val sname = db.rawQuery("select * from Users where acc = ?", arrayOf(userAcc.toString()))
                        if (sname.moveToFirst()){
                            Toast.makeText(this, "账号已存在!", Toast.LENGTH_SHORT).show()
                        }
                        else{
                            val reg_user = User(userAcc.toString(),userPass.toString(),0,0)
                            UserDatabaseUtil().insert(this,reg_user)
                            /**
                             * 获取数据库版本号,并保存新的版本号
                             */
//                            if (load("ver").isNotEmpty()){
//                                ver = load("ver").toInt()
//                            }
//                            save(ver+1,"ver")
                            val dbHero = HeroDatabase(this,"Hero.db",ver,userAcc.toString())
                            dbHero.writableDatabase

                            Toast.makeText(this,"账号注册成功",Toast.LENGTH_SHORT).show()
                            ActivityCollector.removeActivity(this)
                            this.finish()
                            }
                        sname.close()
                    }
                    else{
                        Toast.makeText(this,"两次输入的密码不一致",Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    Toast.makeText(this, "账号不能包含特殊字符！", Toast.LENGTH_SHORT).show()
                }
            }
            else {
                Toast.makeText(this, "请输入完整的内容！", Toast.LENGTH_SHORT).show()
            }
        }
        regText.setOnClickListener {
            val intent = Intent(this,ShowRegTextActivity::class.java)
            startActivity(intent)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }
    private fun save(inputText: Int,data:String) {
        try {
            val output = openFileOutput(data, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText.toString())
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    private fun load(data:String): String {
        val content = StringBuilder()

        try {
            val input = openFileInput(data)
            //val reader = BufferedReader(InputStreamReader(input))
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
        return content.toString()
    }

    private fun withSimbol(str:String):Boolean{
        val len = str.length
        for (i in 0 until len){
            if (!(str[i]>='0'&&str[i]<='9')&&!(str[i]>='a'&&str[i]<='z')&&!(str[i]>='A'&&str[i]<='Z')){
                return true
            }
        }
        return false
    }
}
